<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Option;
use App\Product;
use Auth;

class OptionController extends Controller
{

    public function __construct()
    {
        $this->middleware('auth', [
            'except' => []
        ]);
    }

    /**
     * [option 期权界面]
     * @return [type] [description]
     */
    public function index(Request $request, Product $product)
    {
        $leftDays = Auth::user()->contractsTime();

        return view('home.option', ['product_id' => $product->id,'leftDays' => $leftDays]);
    }


    /**
     * [jsonPoint 折线图数据]
     * @return [type] [description]
     * 买入买权 LongCall（0，1）. 卖出买权 ShortCall（0，-1）
     * 买入卖权 LongPut（-1，0）. 卖出卖权 ShortPut（1，0）
     * 多头：买入 ；空头：卖出
     */
    public function jsonPaint(Request $request, Product $product)
    {
        // 期权和期货
        $allData = Auth::user()->options()->where('product_id', $product->id)->orderBy('ExercisePrice','desc')->get();
        // 期权
        $optionData = Auth::user()->options()->where('product_id', $product->id)->where('type', 1)->orderBy('ExercisePrice','desc')->get();
        // 期货
        $futureData = Auth::user()->options()->where('product_id', $product->id)->where('type', 2)->orderBy('ExercisePrice','desc')->get();
        // dd($product->id);
        // 恒生指数
        $index =  Auth::user()->options()->where('product_id', $product->id)->avg('ExercisePrice') * 5;
        // dd($allData->toArray(),$index);
        // 计算坐标点 每条线三个坐标点
        foreach ($allData as $m => $n) {
            //执行价
            $ExercisePrice = $n->ExercisePrice;
            //权利金
            $Premium = $n->Premium;
            //损益图类型
            $type = $n->CallPut.$n->LongShort;
            switch ($type) {
                case 'CallLong':
                     $x1 = 0;
                     $y1 = -$Premium;
                     $x2 = $ExercisePrice;
                     $y2 = -$Premium;
                     $x3 = $index;
                     $y3 = $index-$ExercisePrice-$Premium;
                     $type = array(0,1);
                     break;
                case 'CallShort':
                     $x1 = 0;
                     $y1 = $Premium;
                     $x2 = $ExercisePrice;
                     $y2 = $Premium;
                     $x3 = $index;
                     $y3 = -($index-$Premium-$ExercisePrice);
                     $type = array(0,-1);
                     break;
                case 'PutLong':
                     $x1 = 0;
                     $y1 = $ExercisePrice-$Premium;
                     $x2 = $ExercisePrice;
                     $y2 = -$Premium;
                     $x3 = $index;
                     $y3 = -$Premium;
                     $type = array(-1,0);
                     break;
                case 'PutShort':
                     $x1 = 0;
                     $y1 = -($ExercisePrice-$Premium);
                     $x2 = $ExercisePrice;
                     $y2 = $Premium;
                     $x3 = $index;
                     $y3 = $Premium;
                     $type = array(1,0);
                     break;
                case 'Long':
                     $x1 = 0;
                     $y1 = -$ExercisePrice;
                     $x2 = $ExercisePrice;
                     $y2 = 0;
                     $x3 = $index;
                     $y3 = $index-$ExercisePrice;
                     $type = array(1,1);
                    break;
                case 'Short':
                     $x1 = 0;
                     $y1 = $ExercisePrice;
                     $x2 = $ExercisePrice;
                     $y2 = 0;
                     $x3 = $index;
                     $y3 = -($index-$ExercisePrice);
                     $type = array(-1,-1);
                    break;
            }

            if ($n->type == 1) {
                //按执行价切分斜率并补齐，1线2斜，2线3斜，3线4斜 以此类推
                for ($i=0; $i <= $m-count($futureData)-1; $i++) {
                    array_unshift($type,$type[0]);
                }
                for ($i=0; $i < count($optionData)-$m-1; $i++) {
                    array_push($type,end($type));
                }
                // 执行价数组
                $ExercisePriceArray[] = $n->ExercisePrice;
            } else {
                for ($i=0; $i < count($optionData)-1; $i++) {
                    array_unshift($type,$type[0]);
                }
            }
            //权利金数组
            $PremiumArray[] = $y1;
            //头寸数组
            $temp[] = $type;

            //头寸相加->tan[]，获取结果线头寸走向趋势数组
            $item = array();
            foreach ($temp as $key => $value) {
                foreach ($value as $k => $v) {
                    $item[$k][$key] = $v;
                }
            }

            foreach ($item as $key => $value) {
                $tan[$key] = array_sum($value);
            }

            //期权收益线分布点
            $map[$m][] = array('x'=>$x1,'y'=>$y1);
            $map[$m][] = array('x'=>$x2,'y'=>$y2);
            $map[$m][] = array('x'=>$x3,'y'=>$y3);
        }
        // dd($temp,$tan);
        //组合循环数据,执行价拐点处首位补齐0和index
        array_unshift($ExercisePriceArray, 0);
        array_push($ExercisePriceArray,$index);
        // 降序排序
        asort($ExercisePriceArray);
        $ExercisePriceArray = array_values($ExercisePriceArray);
        //补齐最后点位的斜率
        array_push($tan,end($tan));

        //权利金初试累计
        $PremiumTotal = array_sum($PremiumArray);

        //第一个拐点和之后的拐点区分，之后的拐点权利金累加
        foreach ($tan as $key => $value) {
            if($key == 0){
                $result[] = array('x'=>$ExercisePriceArray[$key],'y'=>($value*$ExercisePriceArray[$key]+$PremiumTotal));
            }else{
                $result[] = array('x'=>$ExercisePriceArray[$key],'y'=>($tan[$key-1]*($ExercisePriceArray[$key]-$ExercisePriceArray[$key-1])+$PremiumLastTime));
            }
            //累计权益得失
            $PremiumLastTime = $result[$key]['y']?$result[$key]['y']:0;
        }

        // dump($ExercisePriceArray);
        // dump($PremiumTotal);
        // dump($temp);
        // dump($tan);
        // dd($result);

        //结果线
        $map[] = $result;
        // dd($map);
        return response()->json($map);
    }

    /**
     * [jsonTable 表格一数据]
     * @return [type] [description]
     */
    public function jsonTable(Request $request)
    {
        $product_id = $request->session()->get('product_id');
        $data = Auth::user()->options()->where('type', 1)->where('product_id', $product_id)->get();
        return response()->json($data);
    }

    /**
     * [jsonExport 表格二数据]
     * @return [type] [description]
     */
    public function jsonExport(Request $request)
    {
        $product_id = $request->session()->get('product_id');
        $data = Auth::user()->options()->where('type', 2)->where('product_id', $product_id)->get();
        return response()->json($data);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request,Option $option)
    {
        $data   = $request->all();
        $result = $option->storeData($data);

        return Response()->json($result);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request,Option $option)
    {
        $data   = $request->except('_token');
        $result = $option->where('id',$data['id'])->update($data);

        return Response()->json($result);

    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $delete = Option::destroy($id);

        return Response()->json($delete);
    }
}
